import request, { get, post, put, del } from '@/utils/request'
import COS from 'cos-js-sdk-v5'
import { Loading, Message } from 'element-ui'
const defaultApi = (apiName) => {
  return {
    list: (params) => get(`/${apiName}/list`, params),
    page: (params) => get(`/${apiName}`, params),
    read: (id) => get(`/${apiName}/` + id),
    create: (id, data) => post(`/${apiName}`, {}, data),
    update: (id, data) => put(`/${apiName}/` + id, {}, { ...data, created_time: undefined, id: undefined }),
    delete: (id) => del(`/${apiName}/` + id)
  }
}
export const http = {
  community: defaultApi('community'),
  building: defaultApi('building'),
  house: defaultApi('house'),
  owner: defaultApi('owner'),
}

export const uploadFile = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  return request({
    url: '/upload/file',
    method: 'post',
    data: formData
  })
}

export const uploadFileCos = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  return request({
    url: '/upload/filecos',
    method: 'post',
    data: formData
  })
}

const CosConfig = {
  SecretId: 'AKIDyrdCdszxqgNySzSmy6Bgz9IFzVr32nLk',
  SecretKey: 'INGxznOmzzlQ0PftxoYBhHj4JQREoBKG',
  Bucket: 'parkadmin-1317520468',
  Region: 'ap-nanjing',
  Uin: ''
}
const cos = new COS({
  SecretId: CosConfig.SecretId,
  SecretKey: CosConfig.SecretKey
})

export const uploadFileCosClient = (file) => {
  const loadingInstance = Loading.service({
    lock: true,
    text: '上传中...'
  })
  return new Promise((resolve, reject) => {
    cos.uploadFile({
      Bucket: CosConfig.Bucket, /* 填写自己的 bucket，必须字段 */
      Region: CosConfig.Region, /* 存储桶所在地域，必须字段 */
      Key: file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
      Body: file, // 上传文件对象
      SliceSize: 1024 * 1024 * 10, /* 触发分块上传的阈值，超过5MB 使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
      onProgress: function(progressData) {
        console.log(JSON.stringify(progressData))
      }
    }, function(err, data) {
      loadingInstance.close()
      if (err) {
        Message.error('上传失败')
        reject(err)
      } else {
        Message.success('上传成功')
        resolve({
          data: {
            url: 'https://' + data.Location
          }
        })
      }
    })
  })
}
